<template>
  <div>
    <data-table ref="dataTable" :options="options" :list-query="listQuery" @add="handleAdd" @multi-actions="handleMultiAction">
      <template #filter-content> <el-button v-permission="['qu:batch:add']" type="primary" plain class="filter-item" size="small" icon="el-icon-files" @click="toBatchAdd">
        批量添加
      </el-button> <el-button-group class="filter-item" style="float:  right">
        <el-button v-permission="['qu:import']" size="small" icon="el-icon-upload2" @click="showImport">
          导入
        </el-button>
        <el-button v-permission="['qu:export']" size="small" icon="el-icon-download" @click="exportExcel">
          导出
        </el-button>
      </el-button-group>
        <div style="width: 100%; padding-top: 10px">
          <repo-select ref="repoSelect" v-model="repoId" @code="repoChange" /> <dic-list-select v-model="listQuery.params.quType" dic-code="qu_type" title="请选择题型" style="width: 130px" /> <dic-list-select v-model="listQuery.params.quLevel" dic-code="qu_level" title="难度等级" style="width: 100px" /> <chapter-select v-model="listQuery.params.chapterId" :repo-id="repoId" /> <key-point-tree-select v-model="listQuery.params.pointCodes" :root="pointRoot" /> <el-input v-model="listQuery.params.content" placeholder="试题内容" style="width: 200px;" class="filter-item" size="small" />
        </div>
      </template>
      <template #data-columns>
        <el-table-column label="试题内容" show-overflow-tooltip>
          <template v-slot="scope">
            <detail-link :id="scope.row.id" :title="scope.row.contentText || scope.row.id" to="QuUpdate" permission="qu:update" />
          </template>
        </el-table-column> <el-table-column v-if="repoId == null || repoId===''" label="题库" prop="repoId_dictText" /> <el-table-column label="题型" align="center" width="120px" prop="quType_dictText" /> <el-table-column label="难度" align="center" width="120px" prop="quLevel_dictText" /> <el-table-column label="知识点" show-overflow-tooltip width="200px" prop="pointNames" /> <el-table-column label="章节" align="center" width="200px" prop="chapterId_dictText" /> <el-table-column label="人工批阅" align="center" width="100px">
          <template v-slot="{row}">
            <span v-if="row.manual" class="danger">是</span> <span v-else>否</span>
          </template>
        </el-table-column> <el-table-column label="创建人" align="center" width="120px" prop="createBy_dictText" /> <el-table-column label="操作" fixed="right" align="center" width="120px">
          <template v-slot="scope">
            <el-link type="primary" icon="el-icon-search" @click="viewQu(scope.row.id)">
              预览
            </el-link>
          </template>
        </el-table-column>
      </template>
    </data-table> <el-dialog :close-on-click-modal="false" :visible.sync="chapterDialog" title="批量加入章节" width="30%">
      <el-form v-if="chapterDialog" label-position="left" label-width="100px">
        <el-form-item label="操作章节">
          <chapter-select v-model="chapterForm.chapterId" :repo-id="repoId" />
        </el-form-item>
        <el-row>
          <el-button type="primary" @click="handlerJoinChapters">
            保存
          </el-button>
        </el-row>
      </el-form>
    </el-dialog> <el-dialog :close-on-click-modal="false" :visible.sync="levelDialog" title="设置难易程度" width="30%">
      <el-form v-if="levelDialog" label-position="left" label-width="100px">
        <el-form-item label="难易程度">
          <dic-list-select v-model="levelForm.quLevel" dic-code="qu_level" title="请选择难易程度" />
        </el-form-item>
        <el-row>
          <el-button type="primary" @click="handlerBatchLevel">
            保存
          </el-button>
        </el-row>
      </el-form>
    </el-dialog> <el-dialog :close-on-click-modal="false" :visible.sync="repoDialog" title="批量迁移题库" width="30%">
      <div class="err-box">
        <div>
          1、题库迁移后，会将题库的全部章节清空。
        </div>
        <div>
          2、题库迁移后，试题中非本章节所属的识点的会被移除。
        </div>
      </div>
      <el-form v-if="repoDialog" label-position="left" label-width="100px">
        <el-form-item label="选择题库">
          <repo-select v-model="repoForm.toId" />
        </el-form-item>
        <el-row>
          <el-button type="primary" @click="handlerBatchRepo">
            保存
          </el-button>
        </el-row>
      </el-form>
    </el-dialog> <el-dialog :close-on-click-modal="false" :visible.sync="importDialog" title="导入试题" width="30%">
      <el-descriptions v-if="importDialog" :column="1" border>
        <el-descriptions-item>
          <template slot="label">
            所属题库
          </template>
          <repo-select v-model="repoId" />
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            导入文件
          </template>
          <import-excel v-if="listQuery.params.repoId!=null && listQuery.params.repoId !== ''" :data="{ repoId: listQuery.params.repoId}" title="试题" action="/api/qu/qu/import" template="/api/qu/qu/import/template" @success="importSuccess" />
          <span v-else> 请先选择题库！ </span>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog> <qu-view-dialog :dialog-show.sync="viewDialog" :qu-id="viewQuId" /> <el-dialog :close-on-click-modal="false" :visible.sync="pointsDialog" title="批量设置知识点" width="30%">
      <el-form v-if="pointsDialog" label-position="left" label-width="100px">
        <el-form-item label="选择知识点">
          <key-point-select :root="pointRoot" @change="setBatchPoints" />
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="handlerBatchPoints">
        保存
      </el-button>
    </el-dialog>
  </div>
</template>
<script>
import { exportExcel, joinChapters, clearChapters, batchLevel, batchRepo, batchPoints, clearPoints } from '@/api/qu/qu'
import { getToken } from '@/utils/auth'
import permission from '@/directive/permission'
import QuSelectDialog from '@/views/admin/repo/qu/components/QuSelectDialog.vue'
import QuViewDialog from '@/views/admin/repo/qu/components/QuViewDialog.vue'
import KeyPointTreeSelect from '@/components/KeyPointTreeSelect/index.vue'
import KeyPointSelect from '@/components/KeyPointSelect/index.vue'
import { mapGetters } from 'vuex'

export default {
  name: 'QuList',
  directives: { permission },
  components: { KeyPointSelect, KeyPointTreeSelect, QuViewDialog, QuSelectDialog },
  data() {
    return {

      // 上传头
      header: {},

      // 归属题库ID
      repoId: '',
      repoDetail: {},

      // 章节操作
      chapterDialog: false,
      chapterForm: {
        chapterId: '',
        quIds: ''
      },

      // 难易程度
      levelDialog: false,
      levelForm: {

      },

      // 迁移题库
      repoDialog: false,
      repoForm: {

      },

      importDialog: false,

      listQuery: {
        current: 1,
        size: 10,
        params: {
          content: '',
          quType: '',
          pointRoot: '',
          repoId: this.repoId,
          pointCodes: []
        }
      },

      options: {

        // 可批量操作
        multi: true,

        add: {
          enable: true,
          permission: 'qu:add'
        },
        edit: {
          enable: true,
          permission: 'qu:update',
          router: { name: 'QuUpdate', params: { id: '$id' }}
        },
        delete: {
          enable: true,
          permission: 'qu:delete',
          url: '/api/qu/qu/delete'
        },

        // 批量操作列表
        multiActions: [
          {
            value: 'join-chapter',
            label: '批量加入章节'
          },
          {
            value: 'clear-chapter',
            label: '清除章节'
          },
          {
            value: 'batch-level',
            label: '设置难易程度'
          },
          {
            value: 'batch-repo',
            label: '批量迁移题库'
          },
          {
            value: 'join-points',
            label: '批量添加知识点'
          },
          {
            value: 'remove-points',
            label: '批量移除知识点'
          },
          {
            value: 'clear-points',
            label: '清除知识点'
          }
        ],
        // 列表请求URL
        listUrl: '/api/qu/qu/paging'
      },

      viewDialog: false,
      viewQuId: '',

      pointsDialog: false,
      pointsForm: {
        action: 'join',
        quIds: [],
        pointCodes: []
      },

      pointRoot: ''
    }
  },

  computed: {
    ...mapGetters([
      'siteData'
    ])
  },

  watch: {
    repoId: {
      handler(val) {
        this.listQuery.params.repoId = val
        this.listQuery.params.pointCodes = []
      }
    }
  },

  activated() {
    this.fillQuery()
  },

  created() {
    this.fillQuery()
    this.header = { token: getToken() }
  },
  methods: {

    // 或刷新
    fillQuery() {
      const repoId = this.$route.query.repoId
      if (repoId) {
        this.repoId = repoId
        this.listQuery.params.repoId = repoId
      }

      // 刷新数据
      if (this.$refs.repoSelect) {
        this.$refs.repoSelect.fetchData()
      }


      if (this.$refs.dataTable) {
        this.$refs.dataTable.refresh()
      }
    },

    repoChange(v) {
      this.pointRoot = v.pointCode
    },

    handleMultiAction(obj) {
      if (obj.opt === 'join-chapter') {
        console.log(this.repoId)
        if (!this.repoId) {
          this.$message.info('请先搜索题库再进行此操作！')
          return
        }
        this.chapterDialog = true
        this.chapterForm.quIds = obj.ids
      }

      if (obj.opt === 'clear-chapter') {
        this.handlerClearChapters(obj.ids)
      }

      if (obj.opt === 'batch-level') {
        this.levelDialog = true
        this.levelForm.quIds = obj.ids
      }

      if (obj.opt === 'batch-repo') {
        this.repoDialog = true
        this.repoForm.ids = obj.ids
      }

      if (obj.opt === 'join-points') {
        if (!this.repoId) {
          this.$message.warning('请先搜索题库后再操作！')
          return
        }
        if (!this.pointRoot) {
          this.$message.warning('请先为题库关联根知识点！')
          return
        }
        this.pointsDialog = true
        this.pointsForm.quIds = obj.ids
        this.pointsForm.action = 'join'
      }

      if (obj.opt === 'remove-points') {
        if (!this.repoId) {
          this.$message.warning('请先搜索题库后再操作！')
          return
        }
        if (!this.pointRoot) {
          this.$message.warning('请先为题库关联根知识点！')
          return
        }
        this.pointsDialog = true
        this.pointsForm.quIds = obj.ids
        this.pointsForm.action = 'remove'
      }

      if (obj.opt === 'clear-points') {
        this.handlerClearPoints(obj.ids)
      }
    },

    handlerClearChapters(ids) {
      const postForm = { quIds: ids }

      clearChapters(postForm).then(() => {
        this.$notify({
          title: '成功',
          message: '批量清理章节成功！',
          type: 'success',
          duration: 2000
        })

        this.chapterDialog = false
        this.$refs.dataTable.getList()
        this.$refs.dataTable.clearSelection()
      })
    },

    handlerJoinChapters() {
      joinChapters(this.chapterForm).then(() => {
        this.$notify({
          title: '成功',
          message: '批量加入章节成功！',
          type: 'success',
          duration: 2000
        })

        this.chapterDialog = false
        this.$refs.dataTable.getList()
        this.$refs.dataTable.clearSelection()
      })
    },

    handlerBatchLevel() {
      batchLevel(this.levelForm).then(() => {
        this.$notify({
          title: '成功',
          message: '批量设置难易程度成功！',
          type: 'success',
          duration: 2000
        })

        this.levelDialog = false
        this.$refs.dataTable.getList()
        this.$refs.dataTable.clearSelection()
      })
    },

    handlerBatchRepo() {
      batchRepo(this.repoForm).then(() => {
        this.$notify({
          title: '成功',
          message: '批量迁移题库成功！',
          type: 'success',
          duration: 2000
        })

        this.repoDialog = false
        this.$refs.dataTable.getList()
        this.$refs.dataTable.clearSelection()
      })
    },

    setBatchPoints(val) {
      this.pointsForm.pointCodes = val
    },

    handlerBatchPoints() {
      console.log(this.pointsForm)
      batchPoints(this.pointsForm).then(() => {
        this.$notify({
          title: '成功',
          message: '批量操作知识点成功！',
          type: 'success',
          duration: 2000
        })

        this.pointsDialog = false
        this.$refs.dataTable.getList()
        this.$refs.dataTable.clearSelection()
      })
    },

    handlerClearPoints(ids) {
      // 删除
      this.$confirm('确实要清除选定试题的全部知识点吗？', '提示信息', {
        confirmButtonText: '确定',
        showCancelButton: true,
        showClose: false,
        type: 'warning'
      }).then(() => {
        const postForm = { quIds: ids }
        clearPoints(postForm).then(() => {
          this.$notify({
            title: '成功',
            message: '批量清理知识点成功！',
            type: 'success',
            duration: 2000
          })
          this.$refs.dataTable.getList()
          this.$refs.dataTable.clearSelection()
        })
      })
    },

    exportExcel() {
      // 导出当前查询的数据
      exportExcel(this.listQuery.params)
    },

    showImport() {
      this.importDialog = true
    },

    importSuccess() {
      this.importDialog = false
      this.$refs.dataTable.getList()
    },
    handleAdd() {
      this.$router.push({ path: '/admin/repo/qu/add', query: { repoId: this.repoId }})
    },

    // 预览试题
    viewQu(quId) {
      this.viewDialog = true
      this.viewQuId = quId
    },

    toAiGen() {
      this.$router.push({ name: 'QuAiGen', query: { repoId: this.repoId }})
    },
    toBatchAdd() {
      this.$router.push({ name: 'QuBatchAdd', query: { repoId: this.repoId }})
    }
  }
}
</script>
